﻿using System;
using System.Globalization;
using System.Resources;
using System.Windows.Forms;
using TSites.GUI.Enums;
using TSites.GUI.Languages;
using TSites.Service.Entities;
using VNMessageBox;
using System.Collections.Generic;

namespace TSites.GUI
{
	public partial class frmUpdateCompany : Form
	{
		private ACTION _action;
		public Company CompanyInstance { get; private set; }

		#region Ctors
		
		public frmUpdateCompany()
		{
			InitializeComponent();
		}

		public int EffectedRow { get; private set; }

		public frmUpdateCompany(ACTION act)
			: this()
		{
			_action = act;
		}

		public frmUpdateCompany(ACTION act, Company company)
			: this(act)
		{
			CompanyInstance = company;
			if (act == ACTION.UPDATE)
			{
				FillData();
			}
		}

		#endregion

		#region Events

		private void frmUpdateCompany_Load(object sender, EventArgs e)
		{
			ApplyResource();
		}

		private void btnOK_Click(object sender, System.EventArgs e)
		{
			AddUpdateCompany();
		}

		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void btnAddContractNo_Click(object sender, EventArgs e)
		{
			errorProvider1.Clear();
			CultureInfo culture = CultureInfoFactory.GetInstance();
			ResourceManager rm = new ResourceManager(CultureInfoFactory.BASEDNAME, typeof(frmUpdateCompany).Assembly);

			string contractNo = txtContractNo.Text.Trim();
			if (contractNo.Length == 0)
			{
				errorProvider1.SetError(txtContractNo, rm.GetString("RequiredField", culture));
			}
			else
			{
				if (lsbContractNo.Items.IndexOf(contractNo) > -1)
				{
					errorProvider1.SetError(txtContractNo, string.Format(rm.GetString("ExistedMsg", culture),
						rm.GetString("ClientContractNo", culture)));
				}
				else
				{
					lsbContractNo.Items.Insert(0, contractNo);
					txtContractNo.Text = string.Empty;
				}
			}
		}

		private void btnRemoveContractNo_Click(object sender, EventArgs e)
		{
			RemoveContractNo();
		}

		private void lsbContractNo_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Delete)
			{
				RemoveContractNo();
			}
		}

		private void lsbContractNo_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (lsbContractNo.SelectedIndex != -1 && !btnRemoveContractNo.Enabled)
			{
				btnRemoveContractNo.Enabled = true;
			}
			else if (lsbContractNo.SelectedIndex == -1 && btnRemoveContractNo.Enabled)
			{
				btnRemoveContractNo.Enabled = false;
			}
		}

		/*private void txtCompanyCode_TextChanged(object sender, EventArgs e)
		{
			txtFax.Text = txtFax.Text.ToUpperFast();
			txtFax.Select(txtFax.TextLength, 0);
		}*/

		/*private void btnBrowse_Click(object sender, EventArgs e)
		{
			OpenFileDialog textFileDlg = new OpenFileDialog();
			textFileDlg.CheckFileExists = true;
			textFileDlg.Filter = "JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png|All Files (*.*)|*.*";
			textFileDlg.Multiselect = false;

			if (textFileDlg.ShowDialog() == DialogResult.OK)
			{
				txtVNAddress.Text = textFileDlg.FileName;
			}
		}*/

		#endregion

		#region Methods

		private void FillData()
		{
			if (CompanyInstance != null)
			{
				txtVNName.Text = CompanyInstance.VietnamesName;
				txtENName.Text = CompanyInstance.EnglishName;
				if (CompanyInstance.ContractNos != null)
				{
					lsbContractNo.BeginUpdate();
					foreach (string item in CompanyInstance.ContractNos)
					{
						lsbContractNo.Items.Add(item);
					}
					lsbContractNo.EndUpdate();
				}
				txtDirectorName.Text = CompanyInstance.RepresentedBy;
				txtVNPosition.Text = CompanyInstance.VietnamesPosition;
				txtENPosition.Text = CompanyInstance.EnglishPosition;
				txtTaxCode.Text = CompanyInstance.TaxCode;
				txtPhone.Text = CompanyInstance.Phone;
				txtFax.Text = CompanyInstance.Fax;
				txtVNAddress.Text = CompanyInstance.VietnamesAddress;
				txtENAddress.Text = CompanyInstance.EnglishAddress;
			}
		}

		private void ApplyResource()
		{
			CultureInfo culture = CultureInfoFactory.GetInstance();
			ResourceManager rm = new ResourceManager(CultureInfoFactory.BASEDNAME, typeof(frmUpdateCompany).Assembly);

			lblTaxCode.Text = rm.GetString("ClientTaxCode", culture) + ":";
			lblVNName.Text = rm.GetString("ClientVNName", culture) + ":";
			lblENName.Text = rm.GetString("ClientENName", culture) + ":";
			lblContractNo.Text = rm.GetString("ClientContractNo", culture) + ":";
			lblDirectorName.Text = rm.GetString("ClientRepresentedBy", culture) + ":";
			lblVNPosition.Text = rm.GetString("ClientVNPosition", culture) + ":";
			lblENPosition.Text = rm.GetString("ClientENPosition", culture) + ":";
			lblPhone.Text = rm.GetString("ClientPhone", culture) + ":";
			lblFax.Text = rm.GetString("ClientFax", culture) + ":";
			lblVNAddress.Text = rm.GetString("ClientVNAddress", culture) + ":";
			lblENAddress.Text = rm.GetString("ClientENAddress", culture) + ":";

			btnOK.Text = rm.GetString("Save", culture);
			btnCancel.Text = rm.GetString("Cancel", culture);

			if (_action == ACTION.ADD)
			{
				this.Text = rm.GetString("frmAddCompany", culture);
			}
			else
			{
				this.Text = rm.GetString("frmUpdateCompany", culture);
			}

			txtVNName.WaterMark = txtENName.WaterMark = txtContractNo.WaterMark = txtDirectorName.WaterMark
				= txtVNPosition.WaterMark = txtENPosition.WaterMark = txtTaxCode.WaterMark
				= rm.GetString("RequiredField", culture);
		}

		private void RemoveContractNo()
		{
			int index;
			if ((index = lsbContractNo.SelectedIndex) > -1)
			{
				lsbContractNo.Items.RemoveAt(index);
			}
		}

		private List<string> Convert2List(ListBox.ObjectCollection contractNo)
		{
			List<string> lstContractNo = new List<string>(contractNo.Count);
			foreach (string item in contractNo)
			{
				lstContractNo.Add(item);
			}

			return lstContractNo;
		}

		private void AddUpdateCompany()
		{
			errorProvider1.Clear();
			CultureInfo culture = CultureInfoFactory.GetInstance();
			ResourceManager rm = new ResourceManager(CultureInfoFactory.BASEDNAME, typeof(frmUpdateCompany).Assembly);

			string vnName = txtVNName.Text.Trim();
			string enName = txtENName.Text.Trim();
			ListBox.ObjectCollection contractNo = lsbContractNo.Items;
			string directorName = txtDirectorName.Text.Trim();
			string vnPosition = txtVNPosition.Text.Trim();
			string enPosition = txtENPosition.Text.Trim();
			string taxCode = txtTaxCode.Text.Trim();
			string phone = txtPhone.Text.Trim();
			string fax = txtFax.Text.Trim();
			string vnAddress = txtVNAddress.Text.Trim();
			string enAddress = txtENAddress.Text.Trim();

			bool isValid = true;
			string requiredField = rm.GetString("RequiredField", culture);
			// check arguments
			if (vnName.Length == 0)
			{
				errorProvider1.SetError(txtVNName, requiredField);
				isValid = false;
			}
			if (enName.Length == 0)
			{
				errorProvider1.SetError(txtENName, requiredField);
				isValid = false;
			}
			if (contractNo == null || contractNo.Count == 0)
			{
				errorProvider1.SetError(lsbContractNo, requiredField);
				isValid = false;
			}
			if (directorName.Length == 0)
			{
				errorProvider1.SetError(txtDirectorName, requiredField);
				isValid = false;
			}
			if (vnPosition.Length == 0)
			{
				errorProvider1.SetError(txtVNPosition, requiredField);
				isValid = false;
			}
			if (enPosition.Length == 0)
			{
				errorProvider1.SetError(txtENPosition, requiredField);
				isValid = false;
			}
			if (taxCode.Length == 0)
			{
				errorProvider1.SetError(txtTaxCode, requiredField);
				isValid = false;
			}
			if (!isValid) // not valid
			{
				return;
			}

			LANGUAGE language;
			string title;
			CompanySingleton companySingle = CompanySingleton.Instance;
			string action = string.Empty;
			if (_action == ACTION.ADD)
			{
				if (companySingle.CheckCompanyName(vnName, enName, null))
				{
					string msg = string.Format(rm.GetString("ExistedMsg", culture), rm.GetString("ClientName", culture));
					errorProvider1.SetError(txtVNName, msg);
					errorProvider1.SetError(txtENName, msg);
					return;
				}

				CompanyInstance = new Company()
				{
					VietnamesName = vnName,
					EnglishName = enName,
					ContractNos = Convert2List(contractNo),
					RepresentedBy = directorName,
					VietnamesPosition = vnPosition,
					EnglishPosition = enPosition,
					TaxCode = taxCode,
					Phone = phone,
					Fax = fax,
					VietnamesAddress = vnAddress,
					EnglishAddress = enAddress
				};

				try
				{
					EffectedRow = companySingle.Add(CompanyInstance);
					if (EffectedRow < 0)
					{
						action = rm.GetString("ErrorAdd", culture);
					}
				}
				catch (Exception ex)
				{
					language = ConfigurationSingleton.Instance.Language;

					title = rm.GetString("Error", culture);
					if (language == LANGUAGE.Vietnames)
					{
						CMessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					else
					{
						MessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			else // Update
			{
				if (companySingle.CheckCompanyName(vnName, enName, CompanyInstance.ID))
				{
					string msg = string.Format(rm.GetString("ExistedMsg", culture), rm.GetString("ClientName", culture));
					errorProvider1.SetError(txtVNName, msg);
					errorProvider1.SetError(txtENName, msg);
					return;
				}

				CompanyInstance.VietnamesName = vnName;
				CompanyInstance.EnglishName = enName;
				CompanyInstance.ContractNos = Convert2List(contractNo);
				CompanyInstance.RepresentedBy = directorName;
				CompanyInstance.VietnamesPosition = vnPosition;
				CompanyInstance.EnglishPosition = enPosition;
				CompanyInstance.TaxCode = taxCode;
				CompanyInstance.Phone = phone;
				CompanyInstance.Fax = fax;
				CompanyInstance.VietnamesAddress = vnAddress;
				CompanyInstance.EnglishAddress = enAddress;

				try
				{
					EffectedRow = companySingle.Update(CompanyInstance);
					if (EffectedRow < 0)
					{
						action = rm.GetString("ErrorUpdate", culture);
					}
				}
				catch (Exception ex)
				{
					language = ConfigurationSingleton.Instance.Language;
					
					title = rm.GetString("Error", culture);
					if (language == LANGUAGE.Vietnames)
					{
						CMessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					else
					{
						MessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}

			if (EffectedRow < 0)
			{
				string message;
				message = string.Format(rm.GetString("ErrorCompanyMsg", culture), action);
				title = rm.GetString("Error", culture);
				if (ConfigurationSingleton.Instance.Language == LANGUAGE.Vietnames)
				{
					CMessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else
				{
					MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				return;
			}

			this.Close();
		}

		#endregion
	}
}
